﻿using System;

namespace Jerkymon.Cryptography
{
    public class PowerBuilder
    {
		#region Static Methods (5)
		public static int DataOverFlow(int i, int l, int u)
        {
            int OverFlow;

            while ((i < l) || (i > u))
            {
                if (i < l) i = u - (l - i) - 1;
                if (i > u) i = l + (i - u) + 1;
            }

            OverFlow = i;

            return OverFlow;
        }

		public static string Decrypt(string str, string pass)
        {
            return Decrypt(str, pass, true);
        }

		public static string Decrypt(string str, string pass, bool encode)
        {
            if (encode)
                encode = false;
            else
                encode = true;

            return Encrypt(str, pass, encode);
        }

		public static string Encrypt(string str, string pass)
        {
            return Encrypt(str, pass, true);
        }

		/// <summary>
        ///
        /// 
        /// </summary>
        /// <param name="str"></param>
        /// <param name="pass"></param>
        /// <param name="encode"></param>
        /// <returns></returns>
        public static string Encrypt(string str, string pass, bool encode)
        {

            int a, b, x, i, PassCount;
            string TmpStr = "", Crypt = "";  //'make sure that the String is clear			
            PassCount = 0;

            for (x = 0; x <= str.Length - 1; x++)
            {
                a = (int)Convert.ToChar(str.Substring(x, 1));
                b = (int)Convert.ToChar(pass.Substring(PassCount, 1));

                if (encode) b = -b;
                //				i = DataOverFlow(a + b, 1, 255);
                i = DataOverFlow(a + b, 42, 122); // 0-9 and A-Z a=z

                TmpStr = TmpStr + (char)(i);
                PassCount = PassCount + 1;
                if (PassCount > pass.Length) PassCount = 0;
            }

            Crypt = TmpStr;
            return Crypt;
        }
		#endregion
    }
}
